package domain;

import javax.xml.crypto.Data;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 封装响应数据
 */
// HTTP/1.1 200 OK
// Bdpagetype: 1
// Bdqid: 0xbe5c448500013e36
// Cache-Control: private
// Connection: Keep-Alive
// Content-Encoding: gzip
// Content-Type: text/html
// Cxy_all: baidu+ecfa9a7a678ea1f42308ecbb532d9b17
// Date: Mon, 16 Sep 2019 02:49:48 GMT
// Expires: Mon, 16 Sep 2019 02:49:41 GMT
// Server: BWS/1.1
// Set-Cookie: delPer=0; path=/; domain=.baidu.com
// Set-Cookie: BDSVRTM=0; path=/
// Set-Cookie: BD_HOME=0; path=/
// Set-Cookie: H_PS_PSSID=1435_21105_29523_29518_29721_29568_29221_28704; path=/; domain=.baidu.com
// Strict-Transport-Security: max-age=172800
// Vary: Accept-Encoding
// X-Ua-Compatible: IE=Edge,chrome=1
// Transfer-Encoding: chunked


public class HttpResponse {

    private String vision;          //协议版本
    private String status;          //状态码
    private String msg;             //状态信息
    private List<Header> headers;   //响应头文件
    private HttpRequest httpRequest;//请求信息（包含有效信息）
    private String msg_;            //备注信息




    private final String FILE_PATH = "TOMCAT\\webapp";
    /**
     * 构造方法
     * @param httpRequest
     */
    public HttpResponse(HttpRequest httpRequest) {
        this.httpRequest = httpRequest;
    }

    /**
     * GET and SET method
     */
    public String getVision() {
        return vision;
    }

    public void setVision(String vision) {
        this.vision = vision;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    private List<Header> getHeaders() {
        return headers;
    }

    private void setHeaders(List<Header> headers) {
        this.headers = headers;
    }

    public HttpRequest getHttpRequest() {
        return httpRequest;
    }

    public void setHttpRequest(HttpRequest httpRequest) {
        this.httpRequest = httpRequest;
    }

    public String getMsg_() {
        return msg_;
    }

    public void setMsg_(String msg_) {
        this.msg_ = msg_;
    }

    /**
     * 成员方法
     */
    //
    public void response(String string){
        this.setVision(this.getHttpRequest().getVision());
        this.setStatus("200");
        this.setMsg("OK");

        //发送响应行，响应头，响应空行
        this.write(constructHttpResponse());


        //发送响应体数据(自定义字符串string)
        try {
            this.write(ByteBuffer.wrap(string.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


    }


    public void response() {

        //设置默认资源
        if(this.getHttpRequest().getRequestURI().equals("/")){
            this.getHttpRequest().setRequestURI(this.getHttpRequest().getRequestURI() + "a.txt");
        }


        ByteBuffer byteBuffer = null;
        try {

            InputStream inputStream = new BufferedInputStream(new FileInputStream(FILE_PATH + this.getHttpRequest().getRequestURI()));

            this.setVision(this.getHttpRequest().getVision());
            this.setStatus("200");
            this.setMsg("OK");



            //发送响应行，响应头，响应空行
            this.write(constructHttpResponse());


            byte[] bytes = new byte[1024];
            StringBuilder stringBuilder = new StringBuilder();

            //循环发送响应体数据（循环读取文件并发送）
            int read = inputStream.read(bytes);
            while (read != -1){
                this.write(ByteBuffer.wrap(bytes,0,read));
                read = inputStream.read(bytes);
            }

            //发送响应体数据(附加信息)
            if (this.getMsg_() != null){
                this.write(ByteBuffer.wrap(this.getMsg_().getBytes("UTF-8")));
            }



        }catch (FileNotFoundException e){
            //如果不存在文件进行以下处理
            this.setVision(this.getHttpRequest().getVision());
            this.setStatus("404");
            this.setMsg("Not Found");
            this.setMsg_("Not found any file ......");


            try {
                //发送响应行，响应头，响应空行（没有对应文件时）
                this.write(constructHttpResponse());
                //发送响应体数据(附加信息)（没有对应文件时）
                this.write(ByteBuffer.wrap(this.getMsg_().getBytes("UTF-8")));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
        }catch (IOException e){
            e.printStackTrace();
        }



    }


    //发送http响应

    /**
     * 重载方法
     * private void write(StringBuilder stringBuilder);  对文本数据进行传输
     * private void write(ByteBuffer byteBuffer);        对二进制数据进行传输
     */

    private void write(StringBuilder stringBuilder){
        try {
            SocketChannel socketChannel = (SocketChannel)this.getHttpRequest().getSelectionKey().channel();
            ByteBuffer byteBuffer = ByteBuffer.wrap(new String(stringBuilder).getBytes("utf-8"));
            socketChannel.write(byteBuffer);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
    private void write(ByteBuffer byteBuffer){
        try {
            SocketChannel socketChannel = (SocketChannel)this.getHttpRequest().getSelectionKey().channel();
            socketChannel.write(byteBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    //构建http响应头数据
    private List<Header> constructHeaders(){
        ArrayList<Header> headers = new ArrayList<>();


        //根据访问文件类型对Content-Type头数据进行封装和存储
        String requestURI = this.getHttpRequest().getRequestURI();
        if(requestURI.endsWith("/")){
            headers.add(new Header("Content-Type","text/html; charset=utf-8"));
            this.setMsg_("未设置默认资源");
        }else if(requestURI.endsWith(".jpg")){
            headers.add(new Header("Content-Type","image/jpeg"));
        }else {
            headers.add(new Header("Content-Type","text/html; charset=utf-8"));
        }

        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        headers.add(new Header("Date" , dateFormat.format(date)));



        return headers;
    }


    //构建http响应数据
    private StringBuilder constructHttpResponse() {
        //构建响应行
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(this.getVision() + " " + this.getStatus() + " " + this.getMsg() + "\r\n");

        //构建响应头
        List<Header> headers = constructHeaders();
        if(headers.size() > 0){
            for (Header header:headers) {
                stringBuilder.append(header.toString());
            }
        }


        //添加响应空行
        stringBuilder.append("\r\n");
        return stringBuilder;

    }
}
